<?php


class User extends Connect{
        
    var $user = array();
    var $userId; 
    private $kontaktService;           
    
    private function getNiks(){
        #if($_SESSION['niks']){
        #    return $_SESSION['niks'];
        #}
        $sql = "SELECT * FROM `".PREFIX_STATIC."niks` ";
        if(!$result = DBConnect::query($sql, 'niks') ){       
            $this->_error(mysql_error());
            return false; 
        }
        $_arr = array();
        while($arr = DBConnect::getOne($result, 'niks')){
            #$_SESSION['niks'][$arr['level']] = $arr['name'];
            $_arr[$arr['level']] = $arr['name'];
        }
        #return $_SESSION['niks'];
        return $_arr;
    }
    
    private function getNic($level){
        $a = $this->getNiks();
        $m = 0;
        krsort($a);        
        foreach($a as $key => $val){
            if( intval($key) <= intval($level)  ){
                return $val;
            }
        }
    }
    
    private function isitUser($id){
        return $this->getUser($id, array(), true, false);
    }
    
    private function getUserArr($id, $reload = false){
        $sql = "SELECT * FROM `".PREFIX_TABLE."users`
                 WHERE `kontaktid` = '".$id."'";
        
        if(!$result = DBConnect::query($sql) ){       
            $this->_error(mysql_error());
            return false; 
        }
        $arr = DBConnect::getOne($result);
        if( empty($arr['id']) ){
            $this->_error("Игрок не обнаружен", Connect::$Message);
            return false;
        }
        return $arr;
    } 
    
    function getUser($id, 
                    $_storage = array('progress', 'bonus', 'artifact', 'clothing'),
                    $reload = false, 
                    $cash = true){        
        
        
        if( is_array($_SESSION['user']) 
                    && count($_SESSION['user'] ) > 0 
                    && intval($_SESSION['user']['kontaktid']) == $id
                    && !$reload ){
            if($cash){
                $this->user = $_SESSION['user'];        
                $this->userId = $id;    
            }            
            return $_SESSION['user'];
        } 
            
        if( !$arr = $this->getUserArr($id, $reload) ){
            return false;
        }        
        
        $arr['progress'] = intval( Level::getPercent(intval($arr['level'])+1, $arr['practic']) );
        Level::getPractic(intval($arr['level'])+1);
        $arr['pTonextL'] = intval(Level::$levels[intval($arr['level'])+1]);
        $_arr = $this->getClothing($id);
        $arr['clothing'] = (@array_values( $_arr['clothing'] ) === null )? array() : @array_values( $_arr['clothing'] );
        $arr['artifact'] = (@array_values( $_arr['artifact'] ) === null )? array() : @array_values( $_arr['artifact'] );       
        unset($arr['pet']);                      
        $a = $this->getNiks();
        $arr['nik'] = $this->getNic($arr['level']);
        
        #if(  strftime('%d', $arr['lasttime']) != strftime('%d', time())  ){
        /**
         * 2 суток
        */
        /*
        if(  time() - intval($arr['lasttime']) > 172800  ){            
            $arr['monster'] = 1;
        }
        */                
        #if(  time() - intval($arr['showM']) > 172800  ){            
        if(  time() - intval($arr['showM']) > 600  ){
            $arr['monster'] = 1;
            $arr['showM'] = time();
        }
        
        if($cash){
            $this->user = $arr;        
            $this->userId = $id;
            $_SESSION['user'] = $arr;    
        }
        return $arr;        
    }
    
    public function setLevelTree($user, $level){
        $sql = "UPDATE `".PREFIX_TABLE."users` SET `levelTree` = '".$level."' WHERE `kontaktid` = '".$user."' ";
        if(!$result = DBConnect::query($sql) ){       
            $this->_error(mysql_error());
            return false; 
        }
        return true;
    }
    
    public function setChangeTutorial($user, $type){
        if($this->getUser($user) === false){
            return false;
        }
        $arr = @explode( ",", $this->user['tutorial'] );
        if(is_array($arr)){
            if(array_search($type, $arr) !== false) return true;                
        }else{
            $arr = array();    
        }   
        $arr[] = $type;     
        $str = implode(",", $arr);
        $this->setParams('tutorial', $str);
        return $this->save();
    }
    
    /**
     * прошел хелп
    */
    public function doneHelp($user){
        if($this->getUser($user) === false){
            return false;
        }
        $this->setParams('help', 1);
        return $this->save();
    }
    /**
     * прошел обучение
    */
    public function doneEdu($user){
        if($this->getUser($user) === false){
            return false;
        }
        $this->setParams('edu', 1);
        return $this->save();
    }
    
    public function getSkins($user){
        $storage = new Storage();
        $r = array();                        
        $a = $storage->getMy($user, 'skin', false, true);        
        if(is_array($a) && count($a) > 0) {
            foreach($a as $k => $v){
                $r[] = $v['parent'];
            }
        }        
        return $r;
    }
    
    private function setPractic($user, $practic){        
        /**
         * Заклинание на опыт
        */        
        #if($_SESSION['user']['level'] >= 100) return;
        $mantra = new Mantra($user);
        $practic = $mantra->get('practic', $user, $practic);
        
        $p = $_SESSION['user']['practic'] + $practic;        
        
        #return $_SESSION['user'];        
        $l = Level::getLevel( $_SESSION['user']['level'], $p );
        $_SESSION['user']['level'] = $l['level'] ;
        $_SESSION['user']['practic'] = intval($l['practic']) ;
        $_SESSION['user']['pTonextL'] = intval(Level::$practic[intval($l['level'])+1]); 
        
        #if(Level::$levels[$_SESSION['user']['level'] + 1] <= $_SESSION['user']['practic']){
        
        if($l['level'] > $_SESSION['user']['level']){                        
            
            $_SESSION['user']['timeSetLevel'] = time(); 
            Messages::send($user, "Открыт уровень ".$_SESSION['user']['level']);            
        }
        #Messages::send($user, "Заработан опыт ".$_SESSION['user']['practic']);
        $_SESSION['user']['nik'] = $this->getNic(intval($_SESSION['user']['level']));
        $_SESSION['user']['progress'] = Level::getPercent(intval($_SESSION['user']['level'])+1, $_SESSION['user']['practic']);
        $this->user = $_SESSION['user'];
    }
    
    private function moveMoney($money, $currency){
        $_SESSION['user']['money'.$currency] = $_SESSION['user']['money'.$currency] + $money;
        $this->user = $_SESSION['user']; 
    }
     
    public function save(){
        $_SESSION['user']['lasttime'] = $_SESSION['user']['time'];
        $_SESSION['user']['time'] = time();  
        
        $sql = "UPDATE `".PREFIX_TABLE."users` set ";
        $i = 1;
        $u = $_SESSION['user'];
        unset($u['progress']);
        unset($u['monster']);
        unset($u['artifact']);
        unset($u['clothing']);
        unset($u['mortar']);
        unset($u['boiler']);  
        unset($u['podkova']);
        unset($u['education']);        
        unset($u['mantras']);
        unset($u['bonus']);
        unset($u['pet']);
        unset($u['base']);
        unset($u['attr']);
        unset($u['pTonextL']);
        unset($u['pet']);
        unset($u['levelpet']);
        unset($u['practicpet']);
        unset($u['sessid']);

        foreach($u as $key => $val){
            $sql .= "`".$key."` = '".$val."'";
            $sql .= ($i < count($u))? "," : "" ;
            $i++;    
        }
        $sql .= "  WHERE `kontaktid` = '".$u['kontaktid']."' LIMIT 1";
        
        #return $sql;
        if(!$result = DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false; 
        }
        unset($_SESSION['user']['monster']);
        return true;
    }      
    
    private function setParams($param, $value){
        $_SESSION['user'][$param] = $value;
        $this->user = $_SESSION['user'];
    }
    private function addParams($param, $value){
        $_SESSION['user'][$param][] = $value;
        $this->user = $_SESSION['user'];
    }
    private function delParams($param, $id){
        #unset($_SESSION['user'][$param][$id]);
        foreach($_SESSION['user'][$param] as $key => $val){
            if(intval( $val ) == intval( $id ) ){
                unset($_SESSION['user'][$param][$key]);
                $_SESSION['user'][$param] = array_values($_SESSION['user'][$param]);
            }
        }
        $this->user = $_SESSION['user'];
    }
    
    function getClothing($user, $_arr = array('artifact', 'clothing')){
        if(isset($_SESSION['user']['attr']) ) return $_SESSION['user']['attr']; 
        if(is_array($_arr)){
            $storage = new Storage();
            $_SESSION['user']['attr'] = array();
            foreach($_arr as $val){                
                $a = $storage->getMy($user, $val, false, true);
                if(is_array($a) && count($a) > 0) {
                    foreach($a as $k => $v){
                        #$_SESSION['user']['attr'][$val][] = $v['id'];
                        $_SESSION['user']['attr'][$val][] = $v['parent'];
                    }
                }
                #$_SESSION['user']['attr'][$val] =  $storage->getMy($user, $val, false, true);
                #unset($_SESSION['user']['attr'][$val]['mantra']);
            }            
        }
        return  $_SESSION['user']['attr'];
    }
    
    /**
     * [5357114]
     * [14921442]
     * Ступка, котел, подкова
     * 
    */
    function getAtributes($user){
        $arr = array();
        $storage = new Storage();
        $b = @array_shift( $storage->getMy($user, 'boiler', false, true) );
        $arr[] = array('type' => 'boiler', 'id' => $b['parent']);
        #$arr['mortar'] = @array_shift( $storage->getMy($user, 'mortar', false, true) );
        $b = @array_shift( $storage->getMy($user, 'mortar', false, true) );
        $arr[] = array('type' => 'mortar', 'id' => $b['parent']);;
        #$arr['podkova'] = @array_shift( $storage->getMy($user, 'podkova', false, true) );
        $b = @array_shift( $storage->getMy($user, 'podkova', false, true) );
        $arr[] = array('type' => 'podkova', 'id' => $b['parent']);;
        return $arr;
    }
    
    /**
     * 
    */
    function getCvest($user){
        $this->getUser($user);
        $c = new _Cvest();
        $cvests = $c->get($user, $_SESSION['user']['level']) ;
        #return $cvests;
        $_c = array();
        if(is_array($cvests) && count($cvests) > 0) foreach($cvests as $k => $v){            
            $a = array();
            foreach($v['task'] as $kt => $vt){
                $a[] = $vt;    
            }
            #return $a;
            $cvests[$k]['task'] = $a;
            $_c[] = $cvests[$k];    
        }
        return $_c;
    }
    
    /**
     * лотерея
    */
    function getDraw($user){
        $this->getUser($user);
        #return strftime('%d', $this->user['lasttime']) ."==". strftime('%d', time());        
        if( strftime('%d', $this->user['lasttime']) == strftime('%d', time()) ){
            return false;
        }
        $d = new Draw();
        return $d->getDraw();
    }
    function draw($user, $id){
        $this->getUser($user);
        if( strftime('%d', $this->user['lasttime']) == strftime('%d', time() ) ){
            return false;
        }
        $d = new Draw();
        $r = $d->_draw($id);
        if($r != null){
            $s = new Storage();
            #return $r;
            if( !isset($r['type']) ){
                $r['type'] = "ingredient";
            }
            #return $r;
            if( $s->add($user, $r['type'], $r['id']) !== false ){
                return 1;
            } 
        }
        return 0;
    }
    
    /**
    * подарки раз в день
    */
    function present($user){
        $this->getUser($user);
        /*if( (time() - intval($this->user['lasttime'])) < 604800  ) {
            return false;
        }*/
        if( strftime('%d', $this->user['lasttime']) == strftime('%d', time()) ){
            return false;
        }
        $p = new Present();        
        $arr = $p->getPresent();
        $_a = array();        
        $s = new Storage();
        while($a =  array_pop($arr)){            
            $s->add($user, $a['type'], intval($a['good'])  ) ;
            $_a[] = intval($a['good']);            
        }        
        return $_a;
    } 
    
    /**
     * Реклама 
    */
    function adt($user){        
        $this->getUser($user);        
        if( strftime('%d', $this->user['lasttime']) == strftime('%d', time()) ){
            #return false;
        }
        #Book::getBook();
        $gr = Book::getOfLevels(0, intval($this->user['level']) );
        if(!is_array($gr) || count($gr) == 0) return true;
        
        $green = $gr[rand(0, count($gr) - 1 )];
        $_SESSION['adt'] = array('type' => 'potion', 'id' => $green['id'], 'discount' => intval( rand(50, 95) ) );
        return $_SESSION['adt'];        
    }
    
    
    /**
    * обучение новым рецептам
    */ 
    function education($user){
        if( $this->getUser($user, array()) === false ) return false;
        if( strftime('%d', $this->user['lasttime']) != strftime('%d', time()) ){                       
            $education = new Education();
            $mantra = new Mantra($user);
            $force = $mantra->get('education', $user, $this->user['level']);
            if($force){
                $greens = Book::getOfLevels($this->user['level'], $force);
                $aGreen = array();
                foreach($greens as $k => $v){
                    $aGreen[] = $v['id'];
                }                
                $arr = $education->getNeedEdu($user, $this->user['level'], $aGreen);                
                if(count($arr) == 0){
                    return $education->recipies; 
                }
                $_id = rand(0, count($arr));               
                if( $education->_education($user, $arr[$_id] ) ){
                    Messages::send($user, "Изучен рецепт ".$greens[$arr[$_id]]['level']." уровня");    
                }                         
            }
            
            return $education->recipies; 
        } 
    }
    
    /**
    * Изучить новый рецепт за деньги
    */ 
    function buyEducation($user, $potion){
        if( $this->getUser($user, array()) === false ) return false;
        Book::getBook();
        $g = Book::getGreen($potion);
        if($g === false){
            return false;
        }
        if( floatval($_SESSION['user']['money1']) < floatval( $g['edu1'])){
            $this->_error("Недостаточно средств. Нужно еще ".(floatval( $g['edu1']) - floatval($this->user['money1'])). " ".Exchange::$currency[1]);
            #_echo(3);
            return false;
        }
        if( floatval($_SESSION['user']['money2']) < floatval( $g['edu2'])){
            $this->_error("Недостаточно средств. Нужно еще ".(floatval( $g['edu2']) - floatval($this->user['money2'])). " ".Exchange::$currency[1]);
            #_echo(4);
            return false;
        }                                                                                        
        
        $education = new Education();
        if($education->isEdu($user, $this->user['level'], $g['id']) === true ){
            $this->_error("Уже изучен ");
            return false;
        }               
        if( $education->_education($user, $g['id'] ) ){
            $this->moveMoney( -floatval( $g['edu1']), 1 );
            $this->moveMoney( -floatval( $g['edu1']), 2 );
            Messages::send($user, "Изучен рецепт \"".$g['name']."\" ".$g['level']." уровня");    
        }                         
        if($this->save() ){
            /*$arr = $education->getRecipe($user, $this->user['level']);
            $a = array();
            */
            foreach($education->recipies as $k => $v){
                $a[] = $v['green']; 
            }
            return $a;     
        }
        return false; 
    }
    
    /**
    * Изученые рецепты
    */ 
    function getEduRecipies($user){
        $this->getUser($user, array());
        $education = new Education();
        $arr = $education->getRecipe($user, $this->user['level']);
        $a = array();
        foreach($arr as $k => $v){
            $a[] = $v['green']; 
        }
        return $a; 
    }
    
    
    
    /**
     * 
    */
    function bonus($user){
        $this->getUser($user, array());
        $mantra = new Mantra($user);
        /**
        * добавление эликсиров 
        */
        return $mantra->get('bonuspotion', $user, $this->user);
    }
    
    /**
    * Мои заклинания
    */
    function getMyMantras($user){                
        Magic::getAll();
        $m = new Mantra($user);
        $r = $m->getMOfUsers(array($user));
        #return $r;
        if(is_array($r) && count($r) > 0 ) foreach($r as $k => $vuser){
            $r[$k]['info'] = $a[$k];
            $r[$k]['mantra'] = array();
            foreach($vuser as $k1 => $vmantra){
                #return $k1;
                #if(@count($vmantra) == 0) continue;
                #$r[$k][$k1] = array_values($vmantra);
                if(is_array($vmantra) && count($vmantra) > 0) foreach($vmantra as $km => $vm){
                     if(!$vm) continue; 
                     /*if($vm['usedType'] == 'boiler' ||
                        $vm['usedType'] == 'mortar' ||
                        $vm['podkova'] == 'boiler' ) continue;
                        */ 
                     switch($vm['usedType']){
                        case "potion":
                            $un = Book::getGreen($vm['usedId']);
                        break;
                        default:
                            Goods::getAll();
                            $un = Goods::$all[$vm['usedType']][$vm['usedId']];
                        break; 
                     }                    
                     $vm['usedName'] = $un['name'];                       
                     $r[$k]['mantra'][] = $vm;    
                }
                #$r[$k]['mantra'] = array_merge($r[$k]['mantra'], array_values($vmantra));
                unset($r[$k][$k1]);
            }
        }
        $r['info'] = array_values( Magic::$all );
        return $r;
        /*
        $arrmantras = array();
        $mantra = new Mantra($user);
        return $mantras = $mantra->getMy($user, array('drier', 
                                                'glade', 
                                                'collection', 
                                                'message', 
                                                'replace', 
                                                'practic', 
                                                'bonuspotion',
                                                'education',
                                                'mortar'));
        
        if($mantras['replace']){
            $replace = 0;
            foreach($mantras['replace'] as $key => $val ){
                $replace = $replace + intval($val['value']);
            }
            $mantras['replace'] = $replace;
        }
        
        #Magic::getAll();
        if(count($mantras) > 0) foreach($mantras as $key => $val){
            if(is_array($mantras[$key]) ) foreach($mantras[$key] as $keyM => $valM ){
                $arrmantras[] =  array("from" => $valM["from"],  
                                           #"descript" => Magic::splitDescript( Magic::getDescriptByName($valM ) ),
                                           "descript" => Magic::getDescriptByName( $valM["mantra"] ),
                                           "time" => DBConnect::mysqlDate($valM["time"]),
                                           "totime" => ($valM["timelive"] != 0)? DBConnect::mysqlDate($valM["timelive"]) : "",
                                           "image" => MEDIA_URL.Magic::getImageByName($valM["mantra"]),
                                           "force" => ($valM["force"] != 0)? $valM["force"]." %" : $valM["value"] );
            } 
        }
        return $arrmantras; 
        */
    }
    
    /**
     *  
    */
    function getInfoUsers($user, $players){
        $this->getUser($user, array());
        
        $sql = "SELECT * FROM `".PREFIX_TABLE."users` WHERE ";
        $i = 1;
        foreach($players as $key => $val){
            $sql .= " `kontaktid` = '".$val."'  ";
            $sql .= ($i < count($players) )? " OR  " : "" ;
            $i ++;    
        }
        if( !$result = DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;
        }
        $a = array();
        $p = array();
        while($_arr = DBConnect::getOne($result)){
            $a[$_arr['kontaktid']] = $_arr;
            $p[] = $_arr['kontaktid']; 
        }
        #return $a;
        Magic::getAll();
        $m = new Mantra($user);
        $r = array();
        $r = $m->getMOfUsers($p);
        #return $r;
        if(is_array($r) && count($r) > 0 ) foreach($r as $k => $vuser){
            $r[$k]['info'] = $a[$k];
            $r[$k]['mantra'] = array();
            foreach($vuser as $k1 => $vmantra){
                #$r[$k][$k1] = array_values($vmantra);
                if(is_array($vmantra) && count($vmantra) > 0) foreach($vmantra as $km => $vm){
                     if(!$vm) continue; 
                     if($vm['usedType'] == 'boiler' ||
                        $vm['usedType'] == 'mortar' ||
                        $vm['podkova'] == 'boiler' ) continue;

                     switch($vm['usedType']){
                        case "potion":
                            $un = Book::getGreen($vm['usedId']);
                        break;
                        default:
                            Goods::getAll();
                            $un = Goods::$all[$vm['usedType']][$vm['usedId']];
                        break; 
                     }                    
                     $vm['usedName'] = $un['name'];                                           
                     $r[$k]['mantra'][] = $vm;    
                }
                //$r[$k]['mantra'] = array_merge($r[$k]['mantra'], array_values($vmantra));
                unset($r[$k][$k1]);
            }
        }
        foreach(Magic::$all as $k => $v){
            $v['mantraImage'] = $v['image'];
            unset($v['image']);
            $r['info'][] = $v;                
        }
        #$r['info'] = array_values( Magic::$all );
        return $r;        
    }
    
    
    /**
    */
    function setPeer($user, $peer){
        $sql = "UPDATE `".PREFIX_TABLE."users` SET `peerid` = '".$peer."' 
                WHERE `kontaktid` = '".$user."' "; 
        if(!$result = DBConnect::query($sql) ){       
            $this->_error(mysql_error());
            return false; 
        }
        return true;   
    }
    
    
    function getFrends($user, $frends){
        $sql = "SELECT * FROM `".PREFIX_TABLE."users` ";
        #return $frends;
        if(count($frends) > 0){
            $sql .= " WHERE  ";
            $i = 1;
            foreach($frends as $val) {
                $sql .= " `kontaktid` = '".$val."' ";
                $sql .= ($i < count($frends))? " OR " : "" ;
                $i++;
            }    
        }else{
            return array();
        } 
        if(!$result = DBConnect::query($sql) ){       
            $this->_error(mysql_error());
            return false; 
        }
        #return $frends;
        DBConnect::getAll($result);
        return DBConnect::$all;
    }
    
    
    
    /**
     * 
     * Возвращает зверюгу
    */
    function getPet($id){
        $pet = new Brute();
        if($pet->getPet($id)){
            return $pet->pet;     
        }
        return false;
        /*
        $user = $this->getUser($id, false);
        $pets = Pet::getPets();        
        $arr = array();
        $arr['id'] = $user['pet'];
        $arr['name'] = $pets[$user['pet']]['name'];
        $arr['descript'] = $pets[$user['pet']]['descript'];
        $arr['level'] = $user['levelpet'];
        #$arr['image'] = MEDIA_URL.$pets[$user['pet']]['skins'][$user['levelpet']]['image']; 
        $arr['image'] = $pets[$user['pet']]['skins'][$user['levelpet']]['image'];
        $arr['thumbimage'] = $pets[$user['pet']]['skins'][$user['levelpet']]['thumbimage'];
        return $arr;
        */
    }
    
    /**
     * 
     * Возвращает родовое дерево
    */
    function getTree($id){
        /*$tree = array();
        $tree[1] = "http://cs1692.vkontakte.ru/u5357114/7201f56671172a.zip";
        $tree[2] = "http://cs1692.vkontakte.ru/u5357114/673b96b146a911.zip";
        $tree[3] = "http://cs1692.vkontakte.ru/u5357114/20d58150b5d8af.zip";
        $tree[4] = "http://cs1692.vkontakte.ru/u5357114/2c3de8bed564ff.zip";
        $tree[5] = "http://cs1692.vkontakte.ru/u5357114/6c94feaef623e5.zip";
        $tree[6] = "http://cs1692.vkontakte.ru/u5357114/abc07cdedd9d25.zip";
        $tree[7] = "http://cs1692.vkontakte.ru/u5357114/f73bf8a3c63a3f.zip";
        $tree[8] = "http://cs1692.vkontakte.ru/u5357114/875ae5735e9ca3.zip";
        $tree[9] = "http://cs1692.vkontakte.ru/u5357114/ffb52130b6d672.zip";
        $tree[10] = "http://cs1692.vkontakte.ru/u5357114/b08a65760d547e.zip";
        */
        $t = array_values( Tree::getTree() );
        $user = $this->getUser($id, false);
        $s = new Statistic();
        $v = $s->getPreLastVisit($id);
        #$arr = array($tree, strftime("%d.%m.%Y %H:%M:%S", $user['lasttime']) , strftime("%d.%m.%Y %H:%M:%S", $v['time']));
        $arr = array($t[0], $user['lasttime'] , $v['time']);
        return $arr;
    }
    
    /**
     * 
     * Возвращает то, что в сушилке
    */
    function  getDrier($id){
        $drier = new Drier();
        return $drier->getDrier($id);
    }
    
    
    /**
     * 
    */
    function getAttak($user, $prey){
        $this->getUser($user, array());
        $prey = $this->getUserArr($prey);
        $brute = new Brute();
        $brute->prot($prey['kontaktid'], $this->user);
        return true;
    } 
    
    /**
     * 
     * в сушилку
    */
    function addToDrier($id, $dotid, $prey = false){
        $drier = new Drier();
        $glade = new Glade();
        #$glade->getGlade($id);
        $this->getUser($id, array());
        /*if( $this->getUserArr($id) === false ){
            return false;    
        }*/
        
        if($prey != false ){
            $prey = $this->getUserArr($prey);
            if($prey  === false){
                return false;
            }    
        } 
        $mantra = new Mantra($id);
        #$mantra->getAll($id, array("invisible", "collection", 'glade', 'practic'));
        
        /**
         * Если воровство
        */
        if($prey){
            #return $prey;
            $_glade = $glade->getGladeArr($prey['kontaktid']); 
            #return $_glade;
            #$_glade = $glade->getGlade($prey['kontaktid'], $prey['level']);
            /**
            * Шапка невидимка
            */
            if(!$mantra->get('invisible', $id)){
                $brute = new Brute();                
                
                /*
                $p = $brute->protection($prey['kontaktid'], $this->user);                
                if( $p ){
                    #Сработала защита
                    $this->_error("Вас покусал питомец противника", 1);                    
                    return false;
                }
                */
                $brute->steal($prey['kontaktid'], $this->user);
                #Прибавка опыта 10% от опыта питомца противника
                $this->setPractic($id, ($brute->pet['practicpet']/100)*10 );    
            }
               
        }else{
            $_glade = $glade->getGladeArr($id);
            #$_glade = $glade->getGlade($id, $this->user['level']);            
            #$_glade = $mantra->get('collection', $id, $_glade);
            #return $_glade;
        }
        #return $_glade; 
        #return ($_glade[$dotid]['timedrop'] - time());
        #return $_glade[$dotid]['timedrop'];
        if(intval( $_glade[$dotid]['timedrop'] ) < time()){
            $this->_error("хабар на поляне не обнаружен");
            return false;     
        }
        /**
        * Заклинание collection
        */
        Habars::getHabars();
        $h = $mantra->get('collection', $id, Habars::$habars[ intval($_glade[$dotid]['habar']) ] );                                           
        $e = @array_values( Habars::getLevelElements( intval( $this->user['level']  ), @$h['elements'] ) );
        #return 1;
        
        #return $drier->addDrier($id, $_glade[$dotid]['habar'],time(), $e, Habars::$habars[$_glade[$dotid]['habar']]['type']  );
                    
                    
        if($drier->addDrier($id, 
                    $_glade[$dotid]['habar'],
                    time(), 
                    $e, 
                    Habars::$habars[$_glade[$dotid]['habar']]['type']  ) )                   
        {        
            #$_glade['habars'][$dotid]['habar']['id'] 
            #_echo("habar > ". Habars::$habars[$_glade[$dotid]['habar']]['timelive']);           
            #_echo("time > ". time());            
            $glade->updateDotHabar($_glade[$dotid]['id'], 
                                Habars::$habars[$_glade[$dotid]['habar']]['type'] , 
                                $_glade[$dotid]['habar'],
                                time() - Habars::$habars[$_glade[$dotid]['habar']]['timelive'] -1 );                                    
            /*$glade->takeHabar($_glade[$dotid]['id'], 
                                $_glade[$dotid]['habar'],  
                                time() - Habars::$habars[$_glade[$dotid]['habar']]['timelive'] -1 );
            */
        }
        
        $this->setPractic($id, Habars::$habars[$_glade[$dotid]['habar']]['type']['practic']);
        return  $this->save();       
    }
        
    
    /**
     * 
     * Возвращает то, что на поляне
    */
    function  getGlade($id){
        #return $this->getUser($id, false);
        if( $this->getUser($id, array()) === false ){
            return false;
        }
        #Habars::$reload = true; 
        #хабары нужного ур-ня:       
        #Habars::getLevelHabars($this->user['level']);                
        #Habars::$reload = false;
        $glade = new Glade();
        $g = $glade->getGlade($id, $this->user['level']);
        foreach($g as $k => $v){
            unset($g[$k]['timedrop']);
        }
        return $g;
    }    
    
    /**
     * 
     * Возвращает ингридиенты
    */
    function  getIngridients($id){
        $drier = new Drier();
        $drier->getDrier($id);
        $ingr = new Ingredient();
        return $ingr->getIngridients($id);
    }    
    
    /**
     * 
     * Поваренная книга
    */
    function  getBook($id){
        Book::getBook($id);
        Habars::getHabars();
        foreach(Book::$book as $key => $val){
            #return $val["green"];
            #foreach ($val as $keyglava => $glava){
                foreach($val["green"] as $keygreen => $green){
                    if(count($green["recept"]) > 0) foreach($green["recept"] as $keyrecept => $recept){
                        Book::$book[$key]["green"][$keygreen]["recept"][$keyrecept]["name"] = Habars::$habars[$recept["habar"]]["elements"][$recept["element"]]["name"];
                        Book::$book[$key]["green"][$keygreen]["recept"][$keyrecept]["descript"] = Habars::$habars[$recept["habar"]]["elements"][$recept["element"]]["descript"];    
                        Book::$book[$key]["green"][$keygreen]["recept"][$keyrecept]["image"] = Habars::$habars[$recept["habar"]]["elements"][$recept["element"]]["image"];
                    }
                }
            #} 
        }                
        return Book::$book;
    }              
    
    /**
     * 
     * Сварить зелье  $idgreen, $buyNeed - купить недостающие
    */
    function brewGreen($kontaktId, $id, $buyNeed = false, $currency = 1){        
        
        $drier = new Drier();
        $drier->getDrier($kontaktId);
        
        $ingr = new Ingredient();               
        Book::getGreen($id);
        #return Book::$greens;
        $user = $this->getUser($kontaktId);
        
        #Habars::getHabars();
                
        $elixir = new Elixir();
        if(!Book::$greens[$id]){
            $this->_error("Неизвесный рецепт");
            return false;
        }                
        if($user['level'] < Book::$greens[$id]['level']){
            
            $education = new Education();            
            if($education->isEdu($kontaktId, $this->user['level'], $id ) === false){
                #$this->_error(array('alert' => "Не тот уровень, нужен ".Book::$greens[$id]['level'].", у вас ".$user['level']) );
                $this->_error(array('alert' => "Нада изучит рецепт") );
                return Connect::$__error;    
            }
            #return false;
        }
        
        $array = array();
        if(is_array(Book::$greens[$id]['recept']) && count(Book::$greens[$id]['recept']) > 0) foreach(Book::$greens[$id]['recept'] as $key => $val){
            if($array[$val['element']]) $array[$val['element']]['count']++;
            else{
                $array[$val['element']] = array('count' => $val['count'], 'habar' => $val['habar']);    
            } 
            #$array[$val['element']] = $val['count'];             
        }
        ksort($array);
        #return $array;
        #return $ingr->isIngridient($kontaktId, $array);
        if(!$ingr->isIngridient($kontaktId, $array)){
            
            $arr = array();
            foreach(Connect::$__error['error'] as $key => $val){
                $arr[$key] = intval($val['need']) - intval($val['count']);
            }
            #return $arr;
            /**
             * Действует ли заклинание. Обновить $arr
            */
            $mantra = new Mantra($kontaktId);            
            $arr = $mantra->get('replace', $kontaktId, $arr);
            #return $arr;
            #Докупить нужное
            
            if($buyNeed != false){                
                #return $this->buyHabars($kontaktId, $arr);
                if( !$this->buyHabars($kontaktId, $arr) ){
                    return false;
                }                
                /*while(count($arr) > 0){
                    if( !$this->buyHabars($kontaktId, $arr) ){                        
                        return false;    
                    }                    
                    $arr = $mantra->get('replace', $kontaktId, $arr);
                }*/
            }else{
                if(count($arr) > 0 ){
                    #return $arr;
                    $__error = array();
                    $cost1 = 0;
                    $cost2 = 0;
                    foreach($arr as $key => $val){
                        Habars::getElement($key);
                        #Habars::$elements[$key]['image'] = MEDIA_URL. Habars::$elements[$key]['image'] ;
                        #Habars::$elements[$key]['count'] = $val;
                        $__error['elements'][]= Habars::$elements[$key];
                        $cost1 = $cost1 + (Habars::$elements[$key]['buy1']*$val);                
                        $cost2 = $cost2 + (Habars::$elements[$key]['buy2']*$val);
                    }
                    $__error['cost'] = "Стоимость ".$cost1." золота  и ".$cost2." серебра ";
                    $this->_error($__error, Connect::$Message);
                    return false;                
                }    
            }
        }
        
        if(!$elixir->add($kontaktId, $id, false)){
            return false;
        }
        
        # Удаление из ингридиентов
        if(!$ingr->delIngridient($kontaktId, $array)){
            return false;
        }
        #Messages::send($kontaktId, "Сварено ".Book::$greens[$id]['descript']);
        $this->setPractic($kontaktId,Book::$greens[$id]['practic']);
        
        $stat = new Statistic(); 
        //$stat->setAction($kontaktId, "brew", "potion", $id);
        
        $c = new _Cvest();        
        $c->get($kontaktId, $_SESSION['user']['level']);
        $_c = $c->runTask($_SESSION['user']['kontaktid'], "brew", "potion", $id, 1);         
        if($_c !== false){            
            $this->setParams("money1", ( intval($_c['m1']) + intval( $this->user['money1'] )) );
            $this->setParams("money2", ( intval($_c['m2']) + intval( $this->user['money2'] )) );
            #$this->setParams("practic", ( intval($_c['p']) + intval( $this->user['practic'] )) );
            $this->setPractic($kontaktId, ( intval($_c['p']) + intval( $this->user['practic'] )));
            /*if($this->save()){
                return array( $c->get($kontaktId, $_SESSION['user']['level']) );    
            }else{
                return false;
            } */               
        }                
        return $this->save( );
    } 
    
    
    /**
     * Купить хабар
     * юзер, елемент хабара, количество, валюта(1/2)
     * 
    */
    /*function buyHabar($user, $element, $count, $currency = 1){
        if(Habars::getElement($element)) return false;
        if( floatval($this->user['money'.$currency]) < floatval( Habars::$elements[$element]['buy'.$currency])){
            $this->_error("Недостаточно средств");
            return false;
        }
        $ingr = new Ingredient(); 
        $ingr->addIngrient($user,
                           Habars::$elements[$element]['parent'],
                           Habars::$elements[$element]['type'], 
                           $element);
        $this->moveMoney( -floatval( Habars::$elements[$element]['buy'.$currency]), $currency );
        return $this->save();                
    }*/
    
    /**
     * Купить хабары
     * юзер, елементы хабара, валюта(1/2)
     * array('element' => 'count')
     * 
    */
    function buyHabars($user, $elements, $currency = 1){
        #return $elements;
        $this->getUser($user);
        $summ1 = 0;
        $summ2 = 0;
        
        foreach($elements as $key => $val){
            if(!Habars::getElement($key)) return false;    
            $summ1 = $summ1 + floatval( Habars::$elements[$key]['buy1']) * intval($val);
            $summ2 = $summ2 + floatval( Habars::$elements[$key]['buy2']) * intval($val);
        }
        
        #return Habars::$elements;
        #return $summ2;
        #return $this->user;
        #return $user;
        #return array($summ1, $summ2, $this->user['money1'], $this->user['money2']);
        
        if( floatval($this->user['money1']) < $summ1 || floatval($this->user['money2']) < $summ2){
            $err_text = "Недостаточно средств.\n Нужно еще ";
            $err_text .= ( ($summ1 - floatval($this->user['money1'])) > 0 )? ($summ1 - floatval($this->user['money1']))." золота.\n" : "";
            $err_text .= ( ($summ2 - floatval($this->user['money2'])) > 0 )? ($summ2 - floatval($this->user['money2']))." серебра." : ""; 
            $this->_error($err_text, Connect::$Message );
            return false;
        }
        #return 1;        
        /*$storage = new Storage();
        foreach($elements as $key => $val){                    
            if( !$storage->add($user, 'ingredient', $key, intval($val)) ) return false;            
        }*/
        $this->moveMoney( -$summ1, 1 );
        $this->moveMoney( -$summ2, 2 );
        return $this->save();                
    }
    
    
    /**
    *  Продать хабары
     * юзер, елементы хабара, валюта(1/2)
     * array('element' => 'count')
     * 
    */
    /*function sellHabars( $user, $elements, $currency ){
        $this->getUser($user);
        $ingr = new Ingredient();
        $arr = array();
        $ingridients = $ingr->getIngridients($user, false);
        foreach($elements as $key => $val){
            if( !isset($ingridients[$key]) ){
                $this->_error("Нет элемента для продажи");
                return false;
            } 
            if( !Habars::getElement($key) ) return false;
            $summ = $summ + floatval( Habars::$elements[$key]['buy'.$currency]) * intval($val);
            $arr[$key] = array('count' => $val);
        }
        if( !$ingr->delIngridient($user, $arr)) return false;            
        $this->moveMoney( $summ, $currency );
        return $this->save();    
    }*/
    
    
    /**
     * Купить эликсир
     * юзер, elixirs, валюта(1/2)
     * array('green' => 'count')
     * 
    */
    /*function buyElixirs($user, $elixirs, $currency){
        $this->getUser($user);
        $summ = 0;
        foreach($elixirs as $key => $val){
            if(!Book::getGreen($key)) return false;
            $summ = $summ + floatval( Book::$greens[$key]['buy'.$currency]) * intval($val);
        }
        if( floatval($this->user['money'.$currency]) < $summ){
            $this->_error("Недостаточно средств. Нужно еще ".($summ - floatval($this->user['money'.$currency])));
            return false;
        }
        $elixir = new Elixir(); 
        foreach($elixirs as $key => $val){                    
            for($i = 1; $i <= intval($val); $i++ )
                if(!$elixir->add($user, $key)){
                    return false;
            }            
        }
        $this->moveMoney( -$summ, $currency );
        return $this->save();                
    }*/
    
    
    /**
    *  Продать еликсиры
     * юзер, еликсиры, валюта(1/2)
     * array('elixir' => 'count')
     * 
    */
    /*function sellElixirs( $user, $elixirs, $currency ){
        $this->getUser($user);
        $ingr = new Ingredient();
        $arr = array();
        $ingridients = $ingr->getIngridients($user, false);
        foreach($elements as $key => $val){
            if( !isset($ingridients[$key]) ){
                $this->_error("Нет элемента для продажи");
                return false;
            } 
            if( !Habars::getElement($key) ) return false;
            $summ = $summ + floatval( Habars::$elements[$key]['buy'.$currency]) * intval($val);
            $arr[$key] = array('count' => $val);
        }
        if( !$ingr->delIngridient($user, $arr)) return false;            
        $this->moveMoney( $summ, $currency );
        return $this->save();    
    }*/
    
    
    function getBuy(){
        Shop::getAll(true);
        
        foreach(Shop::$seed as $key => $val){            
            #Shop::$seed[$key]['image'] = Shop::$seed[$key]['habar']['image'];
            Shop::$seed[$key]['name'] = Shop::$seed[$key]['habar']['name'];
            Shop::$seed[$key]['level'] = Shop::$seed[$key]['habar']['level'];
            #Shop::$seed[$key]['descript'] = Shop::$seed[$key]['habar']['descript']; 
            unset(Shop::$seed[$key]['habar']);            
        }
        return array(
            'ingredient' => Shop::$ingridients,
            #'podkova' => Shop::$podkova,
            'potion' => Shop::$elixirs,
            'clothing' => Shop::$clothing,
            'artifact' => Shop::$artifact,
            #'boiler' => Shop::$boiler,
            #'mortar' => Shop::$mortar,
            'seed' => Shop::$seed,
            'food' => Shop::$food,
            'skin' => Shop::$skin,
            'atributes' => array_merge( Shop::$boiler, Shop::$mortar, Shop::$podkova)
            #'pet' => Shop::$pet
        );
    }
    
    
    /**
     * Купить что-то
     * юзер, elixirs, id, count
     * 
    */
    function buySome($user, $good, $id, $count = 1, $save = true){        
        #_echo("> ".$good);
        if( !$arr = Shop::getOne($id, $good )) return false;
        $arr['buy1'] = $arr['buy1'] * $count ;
        $arr['buy2'] = $arr['buy2'] * $count ;
        #return $arr;
        #_echo(2);
        $this->getUser($user);
        #return $_SESSION['user'];
        $body = $arr['body'];
        #$summ = ;
        if(isset($arr['discount'])){
            $arr['buy1'] = max(0, $arr['buy1']- intval( ($arr['buy1']/100)*$arr['discount'] ) ) ;    
            $arr['buy2'] = max(0, $arr['buy2']- intval( ($arr['buy1']/100)*$arr['discount'] ) ) ;
        }
        
        /**
         * реклама
        */        
        if(isset($_SESSION['adt']) && 
                is_array($_SESSION['adt']) && 
                count($_SESSION['adt']) > 0 &&
                $_SESSION['adt']['type'] == $good &&
                $_SESSION['adt']['id'] = $id
                ){
            $arr['buy1'] = max(0, $arr['buy1']- intval( ($arr['buy1']/100)* intval($_SESSION['adt']['discount']) ) );    
            $arr['buy2'] = max(0, $arr['buy2']- intval( ($arr['buy1']/100)* intval($_SESSION['adt']['discount']) ) );    
        }
        /**
         * */
        /*
        if( floatval($_SESSION['user']['money1']) < floatval( $arr['buy1'])){
            $this->_error("Недостаточно средств. Нужно еще ".(floatval( $arr['buy1']) - floatval($this->user['money1'])));            
            return false;
        }
        if( floatval($_SESSION['user']['money2']) < floatval( $arr['buy2'])){
            $this->_error("Недостаточно средств. Нужно еще ".(floatval( $arr['buy2']) - floatval($this->user['money2'])));
            return false;
        }
        */
        
        if( floor($_SESSION['user']['money1']) < floor( $arr['buy1'])){
            $this->_error("Недостаточно средств. Нужно еще ".(floor( $arr['buy1']) - floor($this->user['money1'])));            
            return false;
        }
        if( floor($_SESSION['user']['money2']) < floor( $arr['buy2'])){
            $this->_error("Недостаточно средств. Нужно еще ".(floor( $arr['buy2']) - floor($this->user['money2'])));
            return false;
        }
        
        $storage = new Storage();        
        
        switch($good){
            case "pet":
                $_SESSION['user']['pet'] = $id;
            break;
            case "seed":
                $arr =  array_shift( $arr );
                $id = $arr['parent'];
            break;
            case "skin":                              
                $myG = $storage->getMy($user, $good, false, true) ;
                foreach($myG as $k => $v){
                    $s = Shop::getOne($v['parent'], 'skin');
                    if($s['body'] == $body){
                        $isGood = $v; 
                    }
                }
                if(is_array($isGood) && count($isGood) > 0){
                    _echo("del ".$good);
                    $storage->del($user,$good, $isGood['id']);
                    $this->moveMoney( (floatval( $s['sell1'])), 1 );
                    $this->moveMoney( (floatval( $s['sell2'])), 2 );
                }
            break;
            case "mortar":                
                _echo("get mortar");
                $myG = $storage->getMy($user, $good, false, true) ;
                $isGood = @array_shift( $myG );
                if(is_array($isGood) && count($isGood)){
                    $p = Shop::getOne($isGood['parent'], 'mortar');
                    $storage->del($user,$good, $isGood['id']);
                    $this->moveMoney( (floatval( $p['sell1'])), 1 );
                    $this->moveMoney( (floatval( $p['sell2'])), 2 );
                }
            break;
            case "boiler":
                _echo("get boiler");
                $myG = $storage->getMy($user, $good, false, true) ;
                $isGood = @array_shift( $myG );
                if(is_array($isGood) && count($isGood)){
                    $p = Shop::getOne($isGood['parent'], 'boiler');
                    $storage->del($user,$good, $isGood['id']);
                    $this->moveMoney( (floatval( $p['sell1'])), 1 );
                    $this->moveMoney( (floatval( $p['sell2'])), 2 );
                }
            break;
            case "podkova":
                $myG = $storage->getMy($user, $good, false, true) ;
                $isGood = @array_shift( $myG );
                if(is_array($isGood) && count($isGood)){
                    $p = Shop::getOne($isGood['parent'], 'podkova');
                    $storage->del($user,$good, $isGood['id']);
                    $this->moveMoney( (floatval( $p['sell1'])), 1 );
                    $this->moveMoney( (floatval( $p['sell2'])), 2 );
                }
            break;
        }
        if(!$storage->add($user,$good, $id, array($count))){
            return false;
        }
        
        Magic::getAll();
        $arr['mantra']['mantra'] = Magic::$all[$arr['mantra']['id']]['name'];
        $arr['mantra']['pict'] = $arr['image'];
        $arr['mantra']['usedId'] = $arr['id'];  
        $arr['mantra']['usedType'] = $arr['type'];
        $mantra = new Mantra($user);
        switch($good){            
            case "podkova":
            case "boiler":
            case "mortar":                                
                $mantra->_unuse($isGood['idM']);
                $mantra->_use($user, $user, $arr['mantra']);    
                if(!$storage->_use($user,$good, $id, $mantra->idM)){
                    return false;
                }
            break;
            case "skin":
                if(!$storage->_use( $user,$good, $id )){
                    return false;
                }
            break;
        }

        #_echo("b1 ". $arr['buy1']);
        #_echo("b2 ". $arr['buy2']);
        
        $this->moveMoney( -(floatval( $arr['buy1'])), 1 );
        $this->moveMoney( -(floatval( $arr['buy2'])), 2 );
        #return $arr;
        #_echo("ub1 ".$this->user['money1']);
        #_echo("ub2 ".$this->user['money2']);
        
        $stat = new Statistic();
        $cur = array( floatval( $arr['buy1']), floatval( $arr['buy2'])  );
        $stat->setAction($user, "buy", $good, $id, $cur);
        
        $c = new _Cvest();
        $c->get($user, $_SESSION['user']['level']);
        $_c = $c->runTask($_SESSION['user']['kontaktid'], "buy", $good, $id, $count);       
        if($_c !== false){
            $this->setParams("money1", ( intval($_c['m1']) + intval( $this->user['money1'] )) );
            $this->setParams("money2", ( intval($_c['m2']) + intval( $this->user['money2'] )) );
            #$this->setParams("practic", ( intval($_c['p']) + intval( $this->user['practic'] )) );
            $this->setPractic($user, ( intval($_c['p']) + intval( $this->user['practic'] ))); 
            /*if($this->save()){
                return array( $c->get($kontaktId, $_SESSION['user']['level']) );    
            }else{
                return false;
            } */             
        }    
        
        if($save){             
            $this->save();
            return $this->user;    
        }                
    }
    
    /**
     * Продать что-то
     * юзер, elixirs, валюта(1/2)
     * array('green' => 'count')
     * 
    */
    function sellSome($user, $good, $id, $count = 1){
        
        $count = intval($count);
        if( !$arr = Shop::getOne($id, $good )) return false;               
        $this->getUser($user);        
        $summ1 = floatval( $arr['sell1'])*$count;
        $summ2 = floatval( $arr['sell2'])*$count;
        
        $storage = new Storage();
        #return $storage->isit($user, $good, $id);
        if( !$storage->isit($user, $good, $id) ){
            $this->_error("Товар не найден");
            return false;
        }      
        if(!$storage->del($user,$good, $id, $count)){    
            return false;
        }
        $this->moveMoney( $summ1, 1 );
        $this->moveMoney( $summ2, 2 );
        
        $stat = new Statistic();
        $cur = array( $summ1, $summ2 );
        //$stat->setAction($user, "sell", $good, $id, $cur);
        
        $c = new _Cvest();
        $c->get($user, $_SESSION['user']['level']);
        $_c = $c->runTask($_SESSION['user']['kontaktid'], "buy", $good, $id, $count);
        if($_c !== false){
            $this->setParams("money1", ( intval($_c['m1']) + intval( $this->user['money1'] )) );
            $this->setParams("money2", ( intval($_c['m2']) + intval( $this->user['money2'] )) );
            #$this->setParams("practic", ( intval($_c['p']) + intval( $this->user['practic'] )) );
            $this->setPractic($user, ( intval($_c['p']) + intval( $this->user['practic'] ))); 
            /*if($this->save()){
                return array( $c->get($kontaktId, $_SESSION['user']['level']) );    
            }else{
                return false;
            }*/                
        }
        
        return $this->save();                
    }
    
        /**
     * Продать что-то
     * юзер, friend, 
     * array('green' => 'count')
     * 
    */
    function presentSome($user, $friend, $good, $id){
                
        $storage = new Storage(); 
        $is = $storage->isit($user, $good, $id);
        #return $is;      
        if( !$is || intval(@$is['use']) != 0 ){
            $this->_error("Товар не найден");
            return false;
        }      
        #return $storage->del($user,$good, $id);
        if(!$storage->del($user,$good, /*$is['parent']*/$id)){    
            return false;
        }       
                
        if(!$storage->present($friend, $good,  /*$is['parent']*/$id)){
            return false;    
        }
        
        $stat = new Statistic();
        $cur = array( $summ1, $summ2 );
        //$stat->setAction($user, "present", $good, /*$is['parent']*/$id, $cur);
        
        $c = new _Cvest();
        $c->get($user, $_SESSION['user']['level']);
        $_c = $c->runTask($_SESSION['user']['kontaktid'], "present", $good, /*$is['parent']*/$id, 1);
        #return $_c;
        if($_c !== false){
            $this->setParams("money1", ( intval($_c['m1']) + intval( $this->user['money1'] )) );
            $this->setParams("money2", ( intval($_c['m2']) + intval( $this->user['money2'] )) );
            #$this->setParams("practic", ( intval($_c['p']) + intval( $this->user['practic'] )) );
            $this->setPractic($user, ( intval($_c['p']) + intval( $this->user['practic'] ))); 
            /*if($this->save()){
                return array( $c->get($kontaktId, $_SESSION['user']['level']) );    
            }else{
                return false;
            } */           
        }
        
        return $this->save();                
    }
    
    /**
     * Мое хранилище
     * юзер, type
     * 
    */
    function getMyStorage($user, $good, $index = true, $id = false, $use = false){
        $storage = new Storage(); 
        if($good == "ingredient"){
            $drier = new Drier();
            $drier->getDrier($user);
        }       
        $all = $storage->getMy($user, $good, $id, $use);
        #return $all;
        if(!$all && Connect::$__error != ''){
            return false;    
        }/*elseif(!$all && Connect::$__error == ''){
            return true;
        } */        
        Magic::getAll();
        $_a = array();
        if(is_array($all)) foreach($all as $key => $val){
            
            /*if($val['mantra']){                
                $all[$key]['descript'] = Magic::splitDescript( Magic::getDescript($val['mantra']) );
                unset($all[$key]['mantra']);    
            }
            */
            switch ($good){
                case "ingredient":
                    $_a[] = array(
                        'id' => $val['element'],
                        'type' => $good,
                        'count' => $val['count'],
                    );
                break;                
                default:
                    $_a[] = array(
                        'id' => $val['parent'],
                        'type' => $good,
                        'count' => $val['count'],
                    );
                break;
            }
            
            
            
            /*
            if($good == 'seed'){
                $all[$key]['image'] = $all[$key]['habar']['image'];
                $all[$key]['name'] = $all[$key]['habar']['name'];
                $all[$key]['descript'] = $all[$key]['habar']['descript']; 
                unset($all[$key]['habar']);
            }
            
            if($index === true){
                $_arr[] = $all[$key];
            }else{
                $_arr[$key] = $all[$key];    
            }*/
            
            
        }       
        return $_a;
    }
    
    /**
     * приглашение
    */
    function referUser($user){
        $mantra = new Mantra($user);
        Magic::$type['glade'] = array('timeLive', 'force', 'message', 'image');
        $m = array();
        $m['timeLive'] = 0;
        $m['force'] = 10;
        $m['mantra'] = 'glade' ;
        $m['id'] = 1 ;
        $m['message'] = 'Скорость роста увеличена на 10%' ;
        $mantra->_use($user, $toUser, $m);
    }
    
    
    /**
     * Использовать заклинание/предмет
     * [юзер, type, id]
    */
    function useSubject($user, $toUser, $type, $id){
        $this->getUser($user);
        
        $storage = new Storage();
        Magic::getAll();
        #$storage->getOne($user, $type, $id);
        
        if( !$arr = $storage->getOne($user, $type, $id)){
            if(Connect::$__error == '') $this->_error("Предмет не найден") ;
            return false;    
        }
        #return $arr;
        $arr = array_shift($arr);
        
        switch($type){
            case "podkova":
            case "mortar":
            case "boiler":
            case "artifact":
            case "clothing":
                Goods::getAll();
                if( !$m = Goods::$all[$type][$arr['parent']] ) return false;
            break;
            case "potion":
                Book::getBook();
                #return Book::getGreen($arr['parent']);
                if( !$m = Book::getGreen($arr['parent']) ) return false;
            break;        
            case "seed":
                Seed::getAll();
                if( !$m = Seed::$all[$arr['parent']] ) return false;
                #return $m; 
                $id = $m['id'];                               
                /*Habars::getHabars();
                $h = Habars::$habars[$m['parent']];*/
            break;
        }
        #return $arr; 
        
        $m['mantra']['mantra'] = Magic::$all[$m['mantra']['id']]['name'];
        $m['mantra']['pict'] = $m['image'];
        $m['mantra']['usedId'] = $m['id'];  
        $m['mantra']['usedType'] = $m['type'];
            
        
        $mantra = new Mantra($user);
        #Одежда
        if($type == "clothing"){
            $clothing = $storage->getMy($user, $type, false, true);
            if(is_array($clothing)) foreach($clothing as $key => $val){
                if( $m['body'] == Goods::$all[$type][$val['parent']]['body']){
                    $this->_error("На эту часть тела уже одето что-то! ");
                    return false;
                }
            }
        }
        #Заклинание ступки, котла, обучения юзаются 1 раз
        if($type == "mortar" || $type == "boiler" || $type == "education" ){
            $mantra->_unuse($arr['idM']);
        }
        
        #return $mantra->__construct($user);
        #return $val['mantra'];
        #return $mantra->_use($user, $toUser, $val['mantra']);
        if($type == "potion" ){
            if($mantra->get('invisible', $user)){
                $u = null;
            }else{
                $u = $user;
            }
            if($arr['bybuy'] != 1){
                #Сварен, юзать заклинание котла boiler
                $m['mantra']['force'] = $mantra->get('boiler', $u, floatval($m['mantra']['force']));    
                #Сварен, юзать заклинание увеличения силы moreforce
                $m['mantra']['force'] = $mantra->get('moreforce', $u, floatval($m['mantra']['force']));
            }
        }
                
        if( $type != 'seed'){
            if( !$mantra->_use($user, $toUser, $m['mantra']) ){
                return false;
            }    
        } 
        #return $user;       
        if( $r = $storage->_use($user, $type, $id, $mantra->idM )){
            switch($type){
                case "clothing":
                    $this->addParams("clothing", $arr['parent']);
                break;
                case "artifact":
                    $this->addParams("artifact", $arr['parent']);
                break;
            }
        }
        
        /**
         * квест
         * */
        $c = new _Cvest();
        $c->get($user, $_SESSION['user']['level']);
        $_c = $c->runTask($_SESSION['user']['kontaktid'], 'use', $type, intval( $id ) , 1);      
        if($_c !== false){
            $this->setParams("money1", ( intval($_c['m1']) + intval( $this->user['money1'] )) );
            $this->setParams("money2", ( intval($_c['m2']) + intval( $this->user['money2'] )) );
            #$this->setParams("practic", ( intval($_c['p']) + intval( $this->user['practic'] )) ); 
            $this->setPractic($user, ( intval($_c['p']) + intval( $this->user['practic'] )));             
        }
        
        /**
        *НА стену
        */
        switch($type){
            case "potion":
            $w = new Wall();
            $wId = $w->add($toUser, $mantra->idM);
            $this->setPractic($user, $m['practic']);
            $this->save();
            return array('postId' => $wId, 'postText' => $mantra->mText);
            break;
        }        
        $this->save();
        return $r;
    }
    
    function getWallPost($postId){
        $w = new Wall();        
        $p = $w->get($postId);
        #return $p;
        $m = new Mantra($p['user']);
        $_m = $m->getOne($p['parent']);
        return $_m;
        if( $_m ){
            $_m['info'] = Magic::getInfo($_m['id']);    
        }
        return $_m;                
    }
    
    
    /**
     * Снять заклинание/предмет
     * [юзер, type, id]
    */
    function unUseSubject($user, $toUser, $type, $id){
        $this->getUser($user);
        $storage = new Storage();
        Magic::getAll();
        
        
        #$arr = $storage->getUse($user, $type, $id);
        #return $arr;
        if( !$arr = $storage->getUse($user, $type, $id) ) return false;
        
        $mantra = new Mantra($user);
        foreach($arr as $key => $val){                        
            #$val['mantra']['mantra'] = Magic::$all[$val['mantra']['id']]['name'];            
            if( !$mantra->_unuse( $val['idM'] ) ){
                return false;
            }        
        }
        if( $r = $storage->_unuse($user, $type, $id)){
            switch($type){
                case "clothing":
                    $this->delParams("clothing", $id);
                break;
                case "artifact":
                    $this->delParams("artifact", $id);
                break;
            }
        }
        return $r;               
    }
    
    
    function first($user){
        include("znahar/settings.php");
        #return $user;
        #_echo("first");
        
        $sql = "INSERT INTO `".PREFIX_TABLE."goods` (`user`, `type`, `parent`, `use`)
               VALUES
               ('".$user."', 'mortar', '".$fMortar."', '1'), 
               ('".$user."', 'boiler', '".$fBoiler."', '1'),
               ('".$user."', 'podkova', '".$fPodkova."', '1'),
               ('".$user."', 'skin', '".$fSkin1."', '1'),
               ('".$user."', 'skin', '".$fSkin2."', '1') ";
        if(!$result = DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;
        }                        
        
        Magic::getAll();
        Goods::getAll();
        $_m = new Mantra($user);
        
        $mantra = Goods::$all['mortar'][$fMortar]['mantra'];
        $mantra['pict'] = Goods::$all['mortar'][$fMortar]['image'];
        $mantra['usedId'] = Goods::$all['mortar'][$fMortar]['id'];  
        $mantra['usedType'] = Goods::$all['mortar'][$fMortar]['type'];
        
        $mantra['mantra'] = Magic::$all[$mantra['id']]['name'];
        if( !$_m->_use($user, $user, $mantra ) ){
            return false;
        }  
        
        $mantra = Goods::$all['boiler'][$fBoiler]['mantra'];
        $mantra['pict'] = Goods::$all['boiler'][$fBoiler]['image'];
        $mantra['usedId'] = Goods::$all['boiler'][$fBoiler]['id'];  
        $mantra['usedType'] = Goods::$all['boiler'][$fBoiler]['type'];
        $mantra['mantra'] = Magic::$all[$mantra['id']]['name'];
        if( !$_m->_use($user, $user, $mantra ) ){
            return false;
        }
        
        $mantra = Goods::$all['podkova'][$fPodkova]['mantra'];
        $mantra['pict'] = Goods::$all['podkova'][$fPodkova]['image'];
        $mantra['usedId'] = Goods::$all['podkova'][$fPodkova]['id'];  
        $mantra['usedType'] = Goods::$all['podkova'][$fPodkova]['type'];
        $mantra['mantra'] = Magic::$all[$mantra['id']]['name'];
        if( !$_m->_use($user, $user, $mantra ) ){
            return false;
        }
        
        
        /**
         * ingredient
        */
        Habars::getHabars();
        $sql = "INSERT INTO `".PREFIX_TABLE."ingredient` (`user`, `habar`, `type`, `element`)
               VALUES";
        $i = 1;
        foreach($fIngredient as $v){            
            $h = Habars::getElement( intval($v) );
            $sql .= "('".$user."', '".$h['parent']."', '".$h['type']."', '".$v."') " ;
            $sql .= ( $i < count($fIngredient) )? ' , ' : '  ' ;
            $i++ ;
        }
        if(!$result = DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;
        }
        /**
         * potions
        */
        $sql = "INSERT INTO `".PREFIX_TABLE."elixir` (`user`, `parent` )
               VALUES";
        $i = 1;
        foreach($fPotion as $p){            
            $sql .= "('".$user."', '".$p."' )" ;
            $sql .= ( $i < count($fPotion) ) ? ' , ' : ' ' ;
            $i++ ;
        }
        if(!$result = DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;
        }
        
        
        $this->getUser($user, array());        
        $this->moveMoney($fMoney1, 1);
        $this->moveMoney($fMoney2, 2);
        return $this->save();
        
        
        #return $this->user;
        #_echo("buy mortar");
        /*$this->buySome($user, 'mortar', $fMortar, 1, false);
        $this->useSubject($user, $user, 'mortar', $fMortar);
        $this->buySome($user, 'boiler', $fBoiler, 1, false);
        $this->useSubject($user, $user, 'boiler', $fBoiler);
        $this->buySome($user, 'podkova', $fPodkova, 1, false);
        $this->useSubject($user, $user, 'podkova', $fPodkova);
        $this->buySome($user, 'skin', $fSkin1, 1, false);
        $this->buySome($user, 'skin', $fSkin2, 1, false);*/
        #$this->useSubject($user, $user, 'skin', 31);
        
        /*$s = $this->save();
        $_SESSION['user'] = array();
        return $s;*/
        
    }
    
    /**
     * Обмен валюты
    */
    function exchange($user, $currency, $count){
        $arr = array('1' => '2', '2' => '1');
        $ex = array('1' => floatval(CURS), '2' => 1/floatval(CURS) );
        
        $this->getUser($user, array());
        if($this->user['money'.$currency] < $count){
            $this->_error("Недостаточно средств");
            return false;
        }
        
        $this->moveMoney( -$count, $currency );         
        $this->moveMoney( $count * $ex[$currency], $arr[$currency] );
        if( !$this->save() ){
            return false;
        }
        return true;
    }
    
    /**
     * Варианты обмена
    */
    function getExchange($user){
        Exchange::getAll();
        $b = array();
        foreach(Exchange::$all as $k => $v){
            $b[] = array('2' => $v['1'],
                         '1' => $v['v'] ,
                         '3' => $v['2']  );
        }
        #return $this->getBalanceVoices($user);
        #$result = $this->getBalanceVoices($user);
        #return $result;
        #if( !$result ){
        #    return false;
        #}
        #sleep(20);           
        return array('balance' => $this->getBalanceVoices($user),
                     'exchange' => $b );
                       
    }
    
    /**
     * Баланс юзера
    */
    function getBalanceVoices($user){
        if( !$this->kontaktService ){
            $this->kontaktService = new Kontakt( $_SESSION['api_id'], 
                        $_SESSION['userId'], $_SESSION['group_id'], 
                        $_SESSION['viewer_id'], $_SESSION['is_app_user'], 
                        $_SESSION['viewer_type'], $_SESSION['auth_key'] );    
        }
        #return  $this->kontaktService->getAppBalance($user);
        if( !$result = $this->kontaktService->getAppBalance($user)){
            $this->_error($this->kontaktService->_error);
            return false;
        }
        return $result;
    }
    
    /**
     * Перевод голосов
    */
    function moveVoices($user, $voices, $currency = 1 ){
        $this->getUser($user, array());
        Exchange::getAll();
        $f = false;
        $m1 = 0;
        $m2 = 0;
        $exchanged = array();
        foreach(Exchange::$all as $k => $v){
            if( intval(Exchange::$all[$k]['v']) == intval($voices) ){
                $m1 = Exchange::$all[$k][1];
                $m2 = Exchange::$all[$k][2];
                $exchanged[1] = Exchange::$all[$k][1];                
                $exchanged[2] = Exchange::$all[$k][2];
                $f = true;
            }
        }
        if( !$f ){
            $this->_error( 'Вариант обмена не найден' );
            return false;                    
        }        
        if( !$this->kontaktService ){
            $this->kontaktService = new Kontakt( $_SESSION['api_id'], 
                        $_SESSION['userId'], $_SESSION['group_id'], 
                        $_SESSION['viewer_id'], $_SESSION['is_app_user'], 
                        $_SESSION['viewer_type'], $_SESSION['auth_key'] );    
        }
        #return $this->kontaktService->getAppBalance(18557049);
        #return floatval($voices);
        if( !$this->kontaktService->_success ){
            $this->_error($this->kontaktService->answer());
            return false;
        } 
        if( !$this->kontaktService->transferVotes( floatval($voices)) ){
            $this->_error(  'У Вас недостаточно голосов! Пополните счёт в Настройках (кнопка над приложением)' );
            return false;        
        }

        $this->moveMoney($m1, $currency);   
        if( !$this->save()){
            $this->kontaktService->transferVotes( floatval( -$voices));
            return false;                    
        }
        $paylog = new Paylog();        
        $paylog->log($user, $voices, $currency, $exchanged[$currency]);
        Messages::send($user, "Начислено ".$exchanged[$currency]." денег" );
        return true;  
    } 
    
    function delAll(){
        $sql = "SELECT `kontaktid` FROM `".PREFIX_TABLE."users` ";
        if(!$result = DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;             
        }
        while($arr = DBConnect::getOne($result)){
            $this->delMe($arr['kontaktid']);            
        }
    }
    
    
    /**
     * Удалить себя
    */
    function delMe($user){
        #return 1;
        $sql = "DELETE FROM `".PREFIX_TABLE."users` WHERE `kontaktid` = '".$user."'";
        DBConnect::query($sql);
        $sql = "DELETE FROM `".PREFIX_TABLE."goods` WHERE `user` = '".$user."'";
        DBConnect::query($sql);
        $sql = "DELETE FROM `".PREFIX_TABLE."elixir` WHERE `user` = '".$user."'";
        DBConnect::query($sql);
        $sql = "DELETE FROM `".PREFIX_TABLE."cvest` WHERE `user` = '".$user."'";
        DBConnect::query($sql);
        $sql = "DELETE FROM `".PREFIX_TABLE."ingredient` WHERE `user` = '".$user."'";
        DBConnect::query($sql);
        $sql = "DELETE FROM `".PREFIX_TABLE."magic` WHERE `user` = '".$user."'";
        DBConnect::query($sql);
        $sql = "DELETE FROM `".PREFIX_TABLE."seed` WHERE `user` = '".$user."'";
        DBConnect::query($sql);
        $sql = "DELETE FROM `".PREFIX_TABLE."messages` WHERE `user` = '".$user."'";
        DBConnect::query($sql);
        $sql = "DELETE FROM `".PREFIX_TABLE."drier` WHERE `user` = '".$user."'";
        DBConnect::query($sql);
        $sql = "DELETE FROM `".PREFIX_TABLE."glade` WHERE `user` = '".$user."'";
        DBConnect::query($sql);
        $sql = "DELETE FROM `".PREFIX_TABLE."recipe` WHERE `user` = '".$user."'";
        DBConnect::query($sql);
        $sql = "DELETE FROM `".PREFIX_TABLE."cvest` WHERE `user` = '".$user."'";
        DBConnect::query($sql);
        if(is_array($_SESSION) && count($_SESSION) > 0) foreach($_SESSION as $k => $v){
            $_SESSION[$k] = null;
            unset($_SESSION[$k]);    
        }  
        return @$_SESSION;      
        return true;
    }
    
    
}

?>